<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.name"
          clearable
          placeholder="输入姓名搜索"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.gender"
          clearable
          size="small"
          placeholder="性别"
          class="filter-item"
          style="width: 80px"
          @change="crud.toQuery"
        >
          <el-option v-for="item in dict.gender_type" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
        <el-select
          v-model="query.nationId"
          clearable
          size="small"
          placeholder="民族"
          class="filter-item"
          style="width: 120px"
          @change="crud.toQuery"
        >
          <el-option v-for="item in dict.nation" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
        <el-select
          v-model="query.politicalId"
          clearable
          size="small"
          placeholder="政治面貌"
          class="filter-item"
          style="width: 130px"
          @change="crud.toQuery"
        >
          <el-option v-for="item in dict.political_climate" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
        <el-select
          v-model="query.isEnable"
          clearable
          size="small"
          placeholder="状态"
          class="filter-item"
          style="width: 100px"
          @change="crud.toQuery"
        >
          <el-option v-for="item in dict.data_status" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="940px"
      >
        <el-form ref="form" inline :model="form" :rules="rules" size="small" label-width="80px">
          <el-tabs v-model="activeName" type="card">
            <el-tab-pane label="基础信息" name="first">
              <el-container>
                <el-main>
                  <el-row :gutter="0.5" class="el-row">
                    <el-col :span="12">
                      <el-form-item label="姓名">
                        <el-select
                          v-model="form.name"
                          clearable
                          filterable
                          remote
                          :remote-method="remoteMethod"
                          :loading="loading"
                          placeholder="请选择"
                          value-key="form.teacherId"
                          @change="refresh"
                        >
                          <el-option disabled value="">
                            <el-col style="width: 100px">姓名</el-col>
                            <el-col style="width: 100px">性别</el-col>
                            <el-col style="width: 100px">职务</el-col>
                            <el-col style="width: 100px">出生日期</el-col>
                          </el-option>
                          <el-option v-for="item in userInfo" :key="item.id" :label="item.name" :value="item">
                            <el-col style="width: 100px">{{ item.name }}</el-col>
                            <el-col style="width: 100px">{{ item.gender == 0 ? '男' : '女' }}</el-col>
                            <el-col style="width: 100px">{{ item.job }}</el-col>
                            <el-col style="width: 100px">{{ parseTime(item.birthDate, 'yyyy-MM') }}</el-col>
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="职务">
                        <el-input v-model="form.job" class="input" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="0.5" class="el-row">
                    <el-col :span="12">
                      <el-form-item label="性别" prop="gender">
                        <el-radio
                          v-for="item in dict.gender_type"
                          :key="item.id"
                          v-model="form.gender"
                          :label="item.value"
                        >{{ item.label }}
                        </el-radio>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="出生年月" prop="birthDate">
                        <el-date-picker v-model="form.birthDate" type="month" format="yyyy-MM" style="width: 250px;" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="0.5" class="el-row">
                    <el-col :span="12">
                      <el-form-item label="民族" prop="nationId">
                        <el-select v-model="form.nationId" filterable placeholder="请选择" class="input">
                          <el-option
                            v-for="item in dict.nation"
                            :key="item.id"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="政治面貌" prop="politicalId">
                        <el-select v-model="form.politicalId" filterable placeholder="请选择" class="input">
                          <el-option
                            v-for="item in dict.political_climate"
                            :key="item.id"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="0.5" class="el-row">
                    <el-col :span="12">
                      <el-form-item label="任职开始">
                        <el-date-picker
                          v-model="form.jobStartDate"
                          type="date"
                          placeholder="选择日期"
                          value-format="yyyy-MM-dd"
                          style="width: 250px;"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="任职结束">
                        <el-date-picker
                          v-model="form.jobEndDate"
                          type="date"
                          placeholder="选择日期"
                          value-format="yyyy-MM-dd"
                          style="width: 250px;"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-main>
                <el-aside style="width: 160px; padding: 2px; background-color: white;">
                  <el-upload
                    ref="upload"
                    accept="image/jpeg,image/gif,image/png,image/bmp"
                    :limit="1"
                    list-type="picture-card"
                    :class="{ hide: hideUpload }"
                    :on-remove="handleRemove"
                    :on-change="handleChange"
                    :before-upload="beforeUpload"
                    :auto-upload="false"
                    :headers="headers"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    :file-list="fileList"
                    :action="imgFileUploadApi + '?name=' + form.name"
                  >
                    <i class="el-icon-plus" />
                    <div slot="tip" class="el-upload__tip" style="margin: 0; padding: 0; line-height: 20px;">
                      请上传大小不超过100M图片
                    </div>
                  </el-upload>
                </el-aside>
              </el-container>
            </el-tab-pane>

            <el-tab-pane label="个人简介" name="second">
              <el-form-item>
                <SimpleEditor v-model="brief" :is-clear="isClear" style="width: 1060px;border: none;" />
              </el-form-item>
            </el-tab-pane>
          </el-tabs>

          <el-form-item label="状态">
            <el-radio v-for="item in dict.data_status" :key="item.id" v-model="form.isEnable" :label="item.value">{{
              item.label }}
            </el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="upload">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="photoPath" label="生活照" width="60">
          <template slot-scope="scope">
            <el-image
              :src=" baseApi + '/file/图片/' + scope.row.photoPath"
              :preview-src-list="[baseApi + '/file/图片/' + scope.row.photoPath]"
              fit="contain"
              lazy
              class="el-avatar"
            >
              <div slot="error">
                <i class="el-icon-document" />
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="80" />
        <el-table-column prop="gender" label="性别" width="50">
          <template slot-scope="scope">
            {{ dict.label.gender_type[scope.row.gender] }}
          </template>
        </el-table-column>
        <el-table-column prop="birthDate" label="出生年月" width="80">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.birthDate,'{y}-{m}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="nationId" label="民族" width="100">
          <template slot-scope="scope">
            {{ dict.label.nation[scope.row.nationId] }}
          </template>
        </el-table-column>
        <el-table-column prop="politicalId" label="政治面貌" width="100">
          <template slot-scope="scope">
            {{ dict.label.political_climate[scope.row.politicalId] }}
          </template>
        </el-table-column>
        <el-table-column prop="job" label="职务" />
        <el-table-column prop="jobStartDate" label="任职开始日期">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.jobStartDate,'{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="jobEndDate" label="任职结束日期">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.jobEndDate,'{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="brief" label="简介">
          <template slot-scope="scope">
            <div><span
              v-html="scope.row.brief.substring(0, scope.row.brief.length > 40 ? 40 : scope.row.brief.length)"
            /></div>
          </template>
        </el-table-column>
        <br>
        <el-table-column prop="isEnable" label="状态" fixed="right" width="50">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isEnable"
              active-color="#409EFF"
              inactive-color="#F56C6C"
              @change="changeEnabled(scope.row, scope.row.isEnable)"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-permission="['admin','leader:edit','leader:del']"
          label="操作"
          width="120px"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudLeader from '@/api/anniversary/leader'
import {
  get as getTeacher
} from '@/api/anniversary/teacher'
import {
  filterInfo as filterTeacherInfo
} from '@/api/anniversary/teacher'
import CRUD, {
  presenter,
  header,
  form,
  crud
} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import SimpleEditor from '@/components/SimpleEditor'
import {
  mapGetters
} from 'vuex'
import {
  getToken
} from '@/utils/auth'

const defaultForm = {
  id: null,
  name: null,
  teacherId: null,
  gender: 2,
  birthDate: null,
  nationId: null,
  politicalId: null,
  job: null,
  jobStartDate: null,
  jobEndDate: null,
  photoPath: null,
  brief: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  sort: null,
  remark: null,
  isEnable: false
}
export default {
  name: 'Leader',
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    SimpleEditor
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['gender_type', 'data_status', 'nation', 'political_climate'],
  cruds() {
    return CRUD({
      title: '历任领导',
      url: 'api/leader',
      sort: 'id,desc',
      crudMethod: {
        ...crudLeader
      }
    })
  },
  data() {
    return {
      hideUpload: false,
      limitCount: 1,
      loading: false,
      // 编辑器内容
      brief: '',
      isClear: false,
      activeName: 'first',
      userInfo: null,
      headers: {
        'Authorization': getToken()
      },
      fileList: [],
      permission: {
        add: ['admin', 'leader:add'],
        edit: ['admin', 'leader:edit'],
        del: ['admin', 'leader:del']
      },
      rules: {
        name: [{
          required: true,
          message: '名称不能为空',
          trigger: 'blur'
        }]
      },
      queryTypeOptions: [{
        key: 'name',
        display_name: '名称'
      },
      {
        key: 'gender',
        display_name: '性别'
      },
      {
        key: 'nationId',
        display_name: '民族'
      },
      {
        key: 'politicalId',
        display_name: '政治面貌'
      },
      {
        key: 'isEnable',
        display_name: '状态'
      }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'baseApi',
      'imgFileUploadApi'
    ])
  },
  mounted() {
    this.brief = '' // 设置富文本框默认显示内容
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.fileList = []
      if (form.photoPath != null) {
        var url = this.baseApi + '/file/图片/' + form.photoPath
        this.fileList.push({
          name: form.photoPath,
          url: url
        })
        this.hideUpload = this.fileList.length >= this.limitCount
      } else {
        this.hideUpload = false
      }

      if (form.nationId != null) {
        form.nationId = `${form.nationId}`
      }
      if (form.politicalId != null) {
        form.politicalId = `${form.politicalId}`
      }
      if (form.id != null && form.brief != null) {
        this.brief = form.brief
      } else {
        this.brief = ''
      }

      this.activeName = 'first'
      this.queryUserInfo() // 获取教师校友信息

      form.isEnable = `${form.isEnable}`
      form.gender = `${form.gender}`
      form.jobStartDate = `${form.jobStartDate}`
      form.jobEndDate = `${form.jobEndDate}`
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      this.hideUpload = true// 隐藏新增的按钮
      crud.form.brief = this.brief
    },
    // 改变状态
    changeEnabled: function(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.data_status[val] + '" ' + data.name + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudLeader.edit(data).then(res => {
          this.crud.notify(this.dict.label.data_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.isEnable = !data.isEnable
        })
      }).catch(() => {
        data.isEnable = !data.isEnable
      })
    },
    upload() {
      // eslint-disable-next-line eqeqeq
      if (this.fileList.length == 0) {
        this.crud.notify('请先选择要上传的照片', CRUD.NOTIFICATION_TYPE.ERROR)
      } else {
        // 若未修改图片地址，则只提交表单
        // eslint-disable-next-line eqeqeq
        if (this.form.photoPath == this.fileList[0].name) {
          this.crud.submitCU()
        } else {
          // 若修改了图片地址，则上传文件并提交表单
          this.$refs.upload.submit()
        }
      }
    },
    beforeUpload(file) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/gif' || 'image/png' || 'image/bmp'
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isIMAGE) {
        this.loading = false
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      return isIMAGE && isLt2M
    },
    handleRemove(file, fileList) {
      this.hideUpload = fileList.length >= this.limitCount
    },
    handleSuccess(response, file, fileList) {
      // this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.form.photoPath = response
      console.log(this.baseApi + '/file/图片/' + response)
      this.$refs.upload.clearFiles()
      this.crud.submitCU()
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    handleChange(files, fileList) {
      this.hideUpload = fileList.length >= this.limitCount
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]
      }
    },
    // 查询教师校友
    queryUserInfo(val) {
      getTeacher(null).then(res => {
        this.userInfo = res.content
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          filterTeacherInfo(query).then(res => {
            this.userInfo = res.content
          })
        })
      } else {
        this.userInfo = []
      }
    },
    refresh(val) {
      this.form.name = val.name
      this.form.teacherId = val.id
      this.form.gender = `${val.gender}`
      this.form.birthDate = val.birthDate

      if (val.nationId != null) {
        this.form.nationId = `${val.nationId}`
      }
      if (val.politicalId != null) {
        this.form.politicalId = `${val.politicalId}`
      }
      this.form.jobStartDate = null
      this.form.jobEndDate = null
      this.form.job = val.job
      this.form.brief = val.brief
    }
  }
}
</script>

<style scoped>

</style>

<style>
  .input {
    width: 250px;
  }

  .el-row {
    margin-bottom: 0;
    display: flex;
    flex-wrap: wrap
  }

  .hide /deep/ .el-upload {
    display: none;
    /* 上传按钮隐藏 */
  }
</style>
